import React, { Component } from 'react';
import {
	Form,
	Modal,
	Select,
	Button,
	InputNumber,
	Row,
	Col
} from 'antd';
import { MinusCircleFilled } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import styles from '../../index.module.scss';
import { clearEmpty, resetClearEmpty } from 'src/services/DataManage';

interface Iprops {
    modalVisibleValue:boolean
    FieldData:any
    modalVisible:any
    joinComponentFunc:any
	setOutDataFunc:any
}


class ClearEmpty extends Component<Iprops,any> {

    formRef = React.createRef<FormInstance>()

    state = {
    	fieldOrder: [ 0 ],
    	currentField: '',
    	currentType: '',
    	currentFieldText: '',
    }

    handelDel = index => {
    	let flist = JSON.parse( JSON.stringify( this.state.fieldOrder ) );
    	flist.splice( index,1 );
    	this.setState( {
    		fieldOrder: flist
    	} );
    }

    checkNext = ( item ) => {
    	//当三个字段都有填充时，新建下一行
    	if( this.state.currentField && this.state.currentType ) {
    		const formSelectItem = this.state.fieldOrder;
    		let last = formSelectItem[formSelectItem.length - 1];
    		if( item === last ) {
    			formSelectItem.push( last +1 );
    			this.setState( { fieldOrder: formSelectItem,
    				currentField: '', currentType: '', currentFieldText: '', } );
    		}
    	}
    }

    handelSubmit = async () => {
    	this.formRef.current.validateFields().then(
    		async value => {
    			let fdata = Object.keys( value )
    			//挑出不为空的
    				.filter( item => value[item]&&item.indexOf( 'field' ) !== -1 )
    			//挑出都有值的
    				.filter( item => {
    					let flag = item.split( '-' )[1];
    					return value[`split-${  flag}`];
    				} ).map( item => {
    					let flag = item.split( '-' )[1];
    					return {
    						'name': value[`field-${flag}`],
    						'type': value[`split-${flag}`],
    						'length': value[`splitText-${flag}`],
    					};
    				} );

    			let info = null;
    			//编辑修改
    			if( this.props.FieldData.edit ) {
    				const { code,name } = this.props.FieldData;
    				info = await resetClearEmpty( { data: { fields: fdata,componentCode: code,componentName: name,'position': 1 } } );
    			}else {
    				//引入新增
    				info = await clearEmpty( { data: { fields: fdata,modelId: this.props.FieldData.modelId,'position': 1 } } );
    			}
    			if ( info.data.success ) {
    				const data =  info.data.data;
    				let toData = { ...data,
    					form: value,
    					edit: this.props.FieldData.edit,
    					fieldOrder: this.state.fieldOrder,
    					nodeType: 'ClearEmpty',
    					style: { 'primaryColor': '#0066FF' },
    					shape: 'SimplicityNode' };
    				this.props.joinComponentFunc( this.props.FieldData,toData,{} );
    				this.handelCancel();
    			}
    		}
    	);
    }

    handelCancel = () => {
    	this.props.modalVisible( 'fieldClearVisible',false );
    	this.formRef.current.resetFields();
    	let data = this.props.FieldData;
    	delete data.edit;
    	this.props.setOutDataFunc( data );
    	this.setState( {
    		fieldOrder: [ 0 ],
    		currentField: '',
    		currentType: '',
    		currentFieldText: '',
    	} );
    }

    componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
    	if( this.props.modalVisibleValue!== prevProps.modalVisibleValue && this.props.FieldData.form &&this.props.FieldData.edit ) {
    		this.formRef.current.setFieldsValue( this.props.FieldData.form );
    		this.setState( { fieldOrder: this.props.FieldData.fieldOrder } );
    	}

    }

    render() {
    	let title = '清除空格';
    	if( this.props.FieldData.edit ) {
    		title += ' (编辑)';
    	}
    	
    	return (
    		<Modal okText={'确定'}
    			cancelText={'取消'}
    			visible={this.props.modalVisibleValue}
    			onOk={this.handelSubmit}
    			onCancel={this.handelCancel}
    			title={title} mask={false} maskClosable={false}>
    			<Form ref={this.formRef}>
    				<Row gutter={[ 16,0 ]} style={{ marginBottom: '8px' }}>
    					<Col span={9}>选择需要清除空格的字段</Col>
    					<Col span={6}>方式</Col>
    					<Col span={4}>位数</Col>
    				</Row>
    				{
    					this.state.fieldOrder.map(
    						( item,index ) => {
    							return (
    								<Row key={item} gutter={[ 16,16 ]}>
    									<Col span={9} >
    										<Form.Item name={`field-${ item}`} noStyle={true}>
    											<Select style={{ width: 150 }} 
    												onChange={value => this.setState( { currentField: value },
    													() => {this.checkNext( item );} ) }>
    												{
    													this.props.FieldData.model.fieldMappings.map(
    														( i,index ) => (
    															// 'i.tempFieldName}'
    															<Select.Option key={index} value={i.tempFieldName}>
    																{i.finalFieldDesc}
    															</Select.Option>
    														) )
    												}
    											</Select>
    										</Form.Item>
    									</Col>
    									<Col span={6}>
    										<Form.Item name={`split-${ item}`} noStyle={true}>
    											<Select style={{ width: 80 }} 
    												onChange={value => this.setState( { currentType: value },
    													() => {this.checkNext( item );} ) }>
    												<Select.Option value={'all'}>全部</Select.Option>
    												<Select.Option value={'left'}>左起</Select.Option>
    												<Select.Option value={'right'}>右起</Select.Option>
    											</Select>
    										</Form.Item>
    									</Col>
    									<Col span={4}>
    										<Form.Item name={`splitText-${item}`} initialValue={0} noStyle={true} >
    											<InputNumber min={0}
    												onChange={value => this.setState( { currentFieldText: value }, 
    													() => {this.checkNext( item );} ) }/>
    										</Form.Item>
    									</Col>
    									<Col push={1} span={1}>
    										{
    											item !== this.state.fieldOrder[this.state.fieldOrder.length -1] ? (
    												<Button type='text' onClick={() => this.handelDel( index )} 
    													icon={<MinusCircleFilled className={ styles.greenBtn } />} />
    											):null
    										}
    									</Col>
    								</Row>
    							);
    						}
    					)
    				}
    			</Form>
    		</Modal>
    	);
    }
}

export default ClearEmpty;